/*
 * @Author: fishroom
 * @Date: 2023-01-05 16:46:25
 * @LastEditTime: 2023-01-09 14:49:12
 * @FilePath: \koa\app\socketHandler\friendHandler.ts
 */
import { Server as ServerIo } from "socket.io";
import socketUserServer from "../server/socketServer/socketUserServer";
import socketGroupServer from "../server/socketServer/socketGroupServer";
import ChitchatUser from "./ChitchatUser";
import ChitchatGroup from "./ChitchatGroup";

export default (
  io: ServerIo,
  userChitchat: Map<string, ChitchatUser>,
  groupChitchat: Map<number, ChitchatGroup>
) => {
  const addFriendById = async function(data: ChitchatUser) {
    try {
      const user = userChitchat.get(data.token || "");
      console.log(user);
      if (user?.token == data.token && data.username == user?.username) {
        const friend: Map<string, ChitchatUser> = new Map(
          Object.entries(JSON.parse(user.friend || "{}"))
        );
        let addFriendId: string = String(data.friend);
        if (friend.has(addFriendId)) {
          return;
        }
        const addFriendInfo: any = await socketUserServer.getUserById(Number(addFriendId));

        friend.set(addFriendId, new ChitchatUser(addFriendInfo));
        user.friend = JSON.stringify(Object.fromEntries(friend));
        await socketUserServer.updataUserById(user);
        return;
      }
    } catch (error) {
      console.log("添加好友出错", error);
    }
  };
  const addGroupById = async function(data: ChitchatUser) {
    try {
      const user = userChitchat.get(data.token || "");
      if (user?.token == data.token && data.username == user?.username) {
        console.log("添加群聊", data);

        let group = groupChitchat.get(Number(data.group));
        let userRest = new ChitchatUser(user);
        group?.member?.set(Number(userRest.user_id), userRest);

        await socketGroupServer.updataGroupById(group);
        if (!(await updataUserGroup(data, user))) {
          return console.log("添加好友出错");
        }
        return;
      }
    } catch (error) {
      console.log("添加好友出错err", error);
    }
  };
  const removeFriendById = function() {};

  const updataUserGroup = async function(data: ChitchatUser, user: ChitchatUser): Promise<boolean> {
    const group: Map<string, ChitchatGroup> = new Map(
      Object.entries(JSON.parse(user.group || "{}"))
    );
    let addGroupId: string = String(data.group);
    if (group.has(addGroupId)) {
      return false;
    }
    const addGroupInfo: any = groupChitchat.get(Number(addGroupId));

    group.set(addGroupId, new ChitchatGroup(addGroupInfo));
    user.group = JSON.stringify(Object.fromEntries(group));
    console.log("添加后的群", user);
    const flag = await socketUserServer.updataUserById(user);
    if (flag != true) {
      console.log(flag);
    }
    return true;
  };

  return {
    addFriendById,
    removeFriendById,
    addGroupById,
  };
};
